#include "Blend.h"



Blender::Blender(Graphics& gfx, bool blending, std::optional<float> factors_in)
	:
	blending(blending)
{
	if (factors_in)
	{
		factors.emplace();
		factors->fill(*factors_in);
	}

	D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC{ CD3D11_DEFAULT{} };
	auto& brt = blendDesc.RenderTarget[0];
	if (blending)
	{
		brt.BlendEnable = TRUE;

		if (factors_in)
		{
			brt.SrcBlend = D3D11_BLEND_BLEND_FACTOR;
			brt.DestBlend = D3D11_BLEND_INV_BLEND_FACTOR;
		}
		else
		{
			brt.SrcBlend = D3D11_BLEND_SRC_ALPHA;
			brt.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
		}
	}
	HR(GetDevice(gfx)->CreateBlendState(&blendDesc, &pBlender));
}

void Blender::Bind(Graphics& gfx) 
{
	const float* data = factors ? factors->data() : nullptr;
	(GetContext(gfx)->OMSetBlendState(pBlender.Get(), data, 0xFFFFFFFFu));
}

void Blender::SetFactor(float factor) 
{
	assert(factors);
	return factors->fill(factor);
}

float Blender::GetFactor() const 
{
	assert(factors);
	return factors->front();
}

std::shared_ptr<Blender> Blender::Create(Graphics& gfx, bool blending, std::optional<float> factor)
{
	return std::make_shared<Blender>(gfx,blending,factor);
}

